package com.decent.common.xss;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import com.decent.common.config.DecentSystemConfig;
import com.decent.common.enums.ErrorCodeEnum;
import com.decent.common.exception.ErrorCodeException;
import com.decent.common.util.http.XssUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * 系统层http请求包装
 *
 * @author wangyx
 */
@Slf4j
public class DecentHttpServletRequestWrapper extends HttpServletRequestWrapper {
    /**
     * 高级别xss防御开关，NORMAL：开启；其他：关闭；
     */
    private final DecentSystemConfig.XssConfig.XssLevelEnum xssProtectLevel;

    public DecentHttpServletRequestWrapper(HttpServletRequest request, DecentSystemConfig.XssConfig.XssLevelEnum xssProtectLevel) {
        super(request);
        this.xssProtectLevel = xssProtectLevel;
    }

    /**
     * xss过滤参数
     * 配合{@link DecentHttpServletRequestWrapper#getParameterValues(java.lang.String)}对key-value形式入参的接口进行xss攻击过滤
     *
     * @param name 入参名
     * @return 过滤后的参数值
     */
    @Override
    public String getParameter(String name) {
        String parameter = super.getParameter(name);
        if (StrUtil.isBlank(parameter)) {
            return null;
        }
        boolean isXssAttack = XssUtil.checkCodeIsXss(parameter);
        if (!isXssAttack) {
            return parameter;
        }
        if (DecentSystemConfig.XssConfig.XssLevelEnum.HIGH.equals(xssProtectLevel)) {
            throw new ErrorCodeException(ErrorCodeEnum.INVALID_PARAMS);
        }
        //过滤参数值
        return HtmlUtil.escape(parameter);
    }

    /**
     * xss过滤参数
     *
     * @param name 入参名
     * @return 过滤后的参数值
     */
    @Override
    public String[] getParameterValues(String name) {
        //获取所有参数值的集合
        String[] results = this.getParameterMap().get(name);
        if (results == null || results.length <= 0) {
            return null;
        }
        int length = results.length;
        for (int i = 0; i < length; i++) {
            boolean isXssAttack = XssUtil.checkCodeIsXss(results[i]);
            if (!isXssAttack) {
                continue;
            }
            if (DecentSystemConfig.XssConfig.XssLevelEnum.HIGH.equals(xssProtectLevel)) {
                throw new ErrorCodeException(ErrorCodeEnum.INVALID_PARAMS);
            }
            //过滤参数值
            results[i] = HtmlUtil.escape(results[i]);
        }
        return results;
    }
}
